/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.AreaManagerLocal;
import com.ez2find.manager.GigCategorieManagerLocal;
import com.ez2find.manager.GigManagerLocal;
import com.ez2find.manager.LocationManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.Area;
import com.ez2find.model.Gig;
import com.ez2find.model.GigCategorie;
import com.ez2find.model.Location;
import com.ez2find.model.RegisterUser;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.RequestContext;
import com.ez2find.util.SessionContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrador
 */
public class GigBean {

    @EJB
    private GigManagerLocal ejbGigManager;
    @EJB
    private GigCategorieManagerLocal ejbGigCategorieManager;
    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private EmailLocal ejbEmail;
    @EJB
    private AreaManagerLocal ejbAreaManager;
    @EJB
    private LocationManagerLocal ejbLocationManager;
    private Gig gig;
    private int back;
    private long gigCategorieId;
    private long areaId;
    private String email1;
    private boolean linkRPOk;
    private boolean createOk;
    private boolean maskedEmail;
    private int page;
    private String searchValue;
    private String searchPayType;
    private boolean onlySearchTitles;
    private boolean hasImage;

    public Gig getGig() {
        if (gig == null) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            HttpSession session = request.getSession();
            if (session.isNew()) {
                try {
                    String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                    externalContext.redirect(errorPageURL);
                    FacesMessage msg = new FacesMessage("The session has bean expired");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    return null;
                }
            } else {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getGig() != null) {
                    gig = sessionBean.getEjbSession().getGig();
                    if(gig.getTypeReplyTo().equals("masked email"))
                        maskedEmail=true;
                    areaId = 0;
                    if (gig.getArea() != null) {
                        areaId = gig.getArea().getId();
                    }
                    gigCategorieId = gig.getGigCategorie().getId();
                } else {
                    gig = new Gig();
                    gig.setPayType("no pay");
                    gig.setTypeReplyTo("masked email");
                    if (!sessionBean.getAreasCurrentSite().isEmpty()) {
                        if (sessionBean.getEjbSession().getCurrentArea() != null) {
                            areaId = sessionBean.getEjbSession().getCurrentArea().getId();
                        } else {
                            areaId = sessionBean.getEjbSession().getCurrentSite().getAreas().get(1).getId();
                        }
                    }
                    try {
                        PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                        back = postBean.getBack();
                    } catch (Exception ex) {
                    }
                }
            }
        }
        return gig;
    }

    public void setGig(Gig gig) {
        this.gig = gig;
    }

    public List<Gig> getlistAll() {
        return ejbGigManager.listAll();
    }

    public String create() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/gigPosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getOwner() != null) {
                    gig.setCode((ejbGigManager.lastCode()) + 1);
                    gig.setType("gig");
                    gig.setUser(sessionBean.getEjbSession().getOwner());
                    gig.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                    if(gig.getTypeReplyTo().equals("masked email"))
                        ejbEmail.addAnonymousEmail("gig", gig.getCode(), gig.getEmail());
                    gig.setPublishDate(new Date(System.currentTimeMillis()));
                    gig.setStatus("active");
                    gig.setCreateDate(new Date(System.currentTimeMillis()));
                    gig.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (areaId != 0) {
                        gig.setArea(ejbAreaManager.find(areaId));
                    }
                    GigCategorie gigCategorie = ejbGigCategorieManager.find(gigCategorieId);
                    gig.setGigCategorie(gigCategorie);
                    gig.setCategorie(gigCategorie.getCategorie());
                    if (gig.getPayType().equals("no pay")) {
                        gig.setCompensation("no pay");
                    }
                    ejbGigManager.create(gig);
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("To manage your post,  log into your account.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    createOk = true;
                    return "success";
                } else {
                    if ((gig.getEmail().length() < 4) || !gig.getEmail().contains("@") || !gig.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !gig.getEmail().equals(email1)) {
                        FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    RegisterUser userAccount = ejbUserManager.findUserByEmail(gig.getEmail());
                    if (userAccount != null) {
                        if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                            gig.setUser(userAccount);
                            gig.setCode((ejbGigManager.lastCode()) + 1);
                            gig.setType("gig");
                            gig.setStatus("pending");
                            gig.setCreateDate(new Date(System.currentTimeMillis()));
                            gig.setSite(sessionBean.getEjbSession().getCurrentSite());
                            if (areaId != 0) {
                                gig.setArea(ejbAreaManager.find(areaId));
                            }
                            GigCategorie gigCategorie = ejbGigCategorieManager.find(gigCategorieId);
                            gig.setGigCategorie(gigCategorie);
                            gig.setCategorie(gigCategorie.getCategorie());
                            if (gig.getPayType().equals("no pay")) {
                                gig.setCompensation("no pay");
                            }
                            ejbGigManager.create(gig);
                            FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            FacesMessage msg1 = new FacesMessage("The User Account from this email " + userAccount.getEmail() + " exist.");
                            FacesContext.getCurrentInstance().addMessage(null, msg1);
                            FacesMessage msg2 = new FacesMessage("If you forgot your password or need to reactive your account clik in the link to recovery password.");
                            FacesContext.getCurrentInstance().addMessage(null, msg2);
                            FacesMessage msg3 = new FacesMessage("Please enter in your account and published your posting.");
                            FacesContext.getCurrentInstance().addMessage(null, msg3);
                            linkRPOk = true;
                            createOk = true;
                            return "success";
                        }
                        //userAccount.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        userAccount.setConfirmationCode(token);
                        ejbUserManager.update(userAccount, false);
                        ejbEmail.sendAccountConfirmation(userAccount);
                        gig.setUser(userAccount);
                    } else {
                        RegisterUser registerUser = new RegisterUser();
                        registerUser.setEmail(gig.getEmail());
                        //registerUser.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        registerUser.setNumberOfPostings(50);
                        registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
                        registerUser.setStatus("pending");
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        registerUser.setConfirmationCode(token);
                        ejbUserManager.create(registerUser);
                        RegisterUser newRegisterUser = ejbUserManager.merge(registerUser);
                        ejbEmail.sendAccountConfirmation(newRegisterUser);
                        gig.setUser(newRegisterUser);
                    }
                    gig.setCode((ejbGigManager.lastCode()) + 1);
                    gig.setType("gig");
                    gig.setStatus("pending");
                    gig.setCreateDate(new Date(System.currentTimeMillis()));
                    gig.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (areaId != 0) {
                        gig.setArea(ejbAreaManager.find(areaId));
                    }
                    GigCategorie gigCategorie = ejbGigCategorieManager.find(gigCategorieId);
                    gig.setGigCategorie(gigCategorie);
                    gig.setCategorie(gigCategorie.getCategorie());
                    if (gig.getPayType().equals("no pay")) {
                        gig.setCompensation("no pay");
                    }
                    ejbGigManager.create(gig);
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("For Administrate your Post eez2find creates an Account for you using the email address " + gig.getEmail() + " to reply this post.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    FacesMessage msg2 = new FacesMessage("Please active your account from email received and published your posting.");
                    FacesContext.getCurrentInstance().addMessage(null, msg2);
                    createOk = true;
                    return "success";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't register");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String previewCreate() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/gigPosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getOwner() != null) {
                gig.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                if (gig.getPayType().equals("no pay")) {
                    gig.setCompensation("no pay");
                }
                return "success";
            } else {
                if ((gig.getEmail().length() < 4) || !gig.getEmail().contains("@") || !gig.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !gig.getEmail().equals(email1)) {
                    FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                if (gig.getPayType().equals("no pay")) {
                    gig.setCompensation("no pay");
                }
                return "success";
            }
        }
    }

    public String update() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if(gig.getTypeReplyTo().equals("masked email") && !maskedEmail)
                    ejbEmail.addAnonymousEmail("gig", gig.getCode(), gig.getEmail());
                if(!gig.getTypeReplyTo().equals("masked email") && maskedEmail)
                    ejbEmail.deleteAnonymousEmail("gig", gig.getCode(), gig.getEmail());
                if (areaId != 0) {
                    gig.setArea(ejbAreaManager.find(areaId));
                } else {
                    gig.setArea(null);
                }
                GigCategorie gigCategorie = ejbGigCategorieManager.find(gigCategorieId);
                gig.setGigCategorie(gigCategorie);
                gig.setCategorie(gigCategorie.getCategorie());
                if (gig.getPayType().equals("no pay")) {
                    gig.setCompensation("no pay");
                }
                ejbGigManager.update(gig);
                FacesMessage msg = new FacesMessage("Successful edit your Post");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                sessionBean.getEjbSession().setGig(null);
                SessionContext.removeAttribute("gigBean");
                return "success";
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't edit");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public long getAreaId() {
        return areaId;
    }

    public void setAreaId(long areaId) {
        this.areaId = areaId;
    }

    public Area getArea() {
        return ejbAreaManager.find(areaId);
    }

    public List<Location> getLocationsGigArea() {
        try {
            return ejbLocationManager.locationsArea(ejbAreaManager.find(areaId));
        } catch (Exception ex) {
            return new ArrayList<Location>();
        }
    }

    public boolean isCreateOk() {
        return createOk;
    }

    public void setCreateOk(boolean createOk) {
        this.createOk = createOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String homeUser() {
        SessionContext.removeAttribute("gigBean");
        return "homeUser";
    }

    public int getBack() {
        return back;
    }

    public void setBack(int back) {
        this.back = back;
    }

    public long getGigCategorieId() {
        if (gigCategorieId == 0) {
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                gigCategorieId = postBean.getCategorieId();
            } catch (Exception ex) {
            }
        }
        return gigCategorieId;
    }

    public void setGigCategorieId(long gigCategorieId) {
        this.gigCategorieId = gigCategorieId;
    }

    public List<Gig> getListGigs() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/gigPosting/list.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            String consult = "";
            boolean gigC = false;
            if (gigCategorieId > 0) {
                consult = consult + " AND g.gigCategorie=:gigCategorie";
                gigC = true;
            }
            if (searchPayType != null && !searchPayType.equals("")) {
                consult = consult + " AND g.payType='" + searchPayType + "'";
            }
            if (hasImage) {
                consult = consult + " AND g.description like '%<img src=%'";
            }
            if (searchValue != null && !searchValue.equals("")) {
                if (onlySearchTitles) {
                    consult = consult + " AND g.title like '%" + searchValue + "%'";
                } else {
                    consult = consult + " AND (g.title like '%" + searchValue + "%' OR g.description like '%" + searchValue + "%')";
                }
            }
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getCurrentArea() == null) {
                return ejbGigManager.listGigsSite(sessionBean.getEjbSession().getCurrentSite(), gigC, ejbGigCategorieManager.find(gigCategorieId), consult);
            } else {
                return ejbGigManager.listGigsArea(sessionBean.getEjbSession().getCurrentArea(), gigC, ejbGigCategorieManager.find(gigCategorieId), consult);
            }
        }
    }

    public String backView() {
        gig = null;
        return "backGig" + back;
    }

    public String backCreate() {
        SessionContext.removeAttribute("gigBean");
        return "back" + back;
    }

    public String backEdit() {
        SessionContext.removeAttribute("gigBean");
        return "back";
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }

    public Date getToDay() {
        return new Date(System.currentTimeMillis());
    }

    public String getDescription() {
        try {
            if (gig.getDescription().contains("\n")) {
                return gig.getDescription().replaceAll("\n", "<br/>");
            } else {
                return gig.getDescription().replaceAll("\r", "<br/>");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "Do not Message";
        }
    }

    public String getSearchValue() {
        if(searchValue==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchValue = postBean.getSearchValue();
            } catch (Exception ex) {
            }
        }
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public boolean isOnlySearchTitles() {
        return onlySearchTitles;
    }

    public void setOnlySearchTitles(boolean onlySearchTitles) {
        this.onlySearchTitles = onlySearchTitles;
    }

    public boolean isHasImage() {
        return hasImage;
    }

    public void setHasImage(boolean hasImage) {
        this.hasImage = hasImage;
    }

    public int getPage() {
        if (page == 0) {
            page = 1;
        }
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getSearchPayType() {
        if(searchPayType==null)
            searchPayType="";
        return searchPayType;
    }

    public void setSearchPayType(String searchPayType) {
        this.searchPayType = searchPayType;
    }
    
    public int getContador(){
        try{
            return 20000-gig.getDescription().length();
        }catch(Exception ex){
            return 20000;
        }
    }
    
    public void setContador(int contador){}
    

    public void flaggingMiscategorized(){
        try {
            gig.setMiscategorized(ejbGigManager.merge(gig).getMiscategorized()+1);
            ejbGigManager.update(gig);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingProhibited(){
        try {
            gig.setProhibited(ejbGigManager.merge(gig).getProhibited()+1);
            ejbGigManager.update(gig);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingSpam(){
        try {
            gig.setSpam(ejbGigManager.merge(gig).getSpam()+1);
            ejbGigManager.update(gig);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingBest(){
        try {
            gig.setBest(ejbGigManager.merge(gig).getBest()+1);
            ejbGigManager.update(gig);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
